﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Microsoft.Practices.CompositeUI.WinForms;
using Microsoft.Practices.CompositeUI;
using Infrastructure.Interface.Constant;

namespace Infrastructure.Shell
{
    public class ShellApplication<TShellForm> : FormShellApplication<WorkItem, TShellForm> where TShellForm : Form
    {
        protected override void AfterShellCreated()
        {
            base.AfterShellCreated();
            ShellForm shellForm = this.Shell as ShellForm;
            RootWorkItem.Items.Add(shellForm.MainToolStripPanel, Constants.MainToolStripPanel);
            RootWorkItem.Items.Add(shellForm.MainStatusStripPanel, Constants.MainStatusStripPanel);
            RootWorkItem.Items.Add(shellForm.DefaultStatusStrip, Constants.DefaultStatusStrip);
            RootWorkItem.Items.Add(shellForm.dockPanel, Constants.DockPanel);
            
        }
        protected override void Start()
        {
            base.Start();
            BindingMenu();
        }

        private void BindingMenu()
        {
            //throw new NotImplementedException();
        }
        #region Unhandled Exception
        public override void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = e.ExceptionObject as Exception;

            if (ex != null)
            {
                MessageBox.Show(BuildExceptionString(ex));
            }
            else
            {
                MessageBox.Show("An Exception has occured, unable to get details");
            }

            Environment.Exit(0);
        }

        private string BuildExceptionString(Exception exception)
        {
            string errMessage = string.Empty;

            errMessage +=
                exception.Message + Environment.NewLine + exception.StackTrace;

            while (exception.InnerException != null)
            {
                errMessage += BuildInnerExceptionString(exception.InnerException);

                exception = exception.InnerException;
            }

            return errMessage;
        }

        private string BuildInnerExceptionString(Exception innerException)
        {
            string errMessage = string.Empty;

            errMessage += Environment.NewLine + " InnerException ";
            errMessage += Environment.NewLine + innerException.Message + Environment.NewLine + innerException.StackTrace;

            return errMessage;
        }
        #endregion
    }
}
